package cn.itsource.org.service.impl;

import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.basic.util.PageList;
import cn.itsource.basic.util.TreeUtil;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Description:
 * @Author: ZHl
 * @Date: 2022-09-11 14:35
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    @Transactional
    public void save(Department department) {
        departmentMapper.insertSelective(department);
        //调用update
        this.update(department);
    }


    @Override
    @Transactional
    public void update(Department department) {  //修改可能会出现自己是自己上级部门的情况

        //插入数据
        Long[] parentIds = department.getParentIds();

        StringBuffer dirPath = new StringBuffer(""); //StringBuffer 当对字符串进行修改的时不会产生新的对象
        if(parentIds != null && parentIds.length !=0){

            Long parentId = parentIds[parentIds.length-1];
            //设置parentId属性值
            department.setParentId(parentId);

            for (Long id : parentIds) {           //[3,4,7,9]   /7
                if(department.getId().equals(id)){   // Long类型的数据判断是否相等最好使用equals
                    throw new RuntimeException("请重新选择上级部门(当前部门的上级部门不能包含当前部门)");
                }
                dirPath.append("/").append(id);   //  /3/4/7/9
            }
            //设置dirPath属性值
            department.setDirPath(dirPath.toString() + "/" + department.getId());  //  /3/4/7/9/自增长id
        }else{
            //设置dirPath属性值
            department.setDirPath("/" + department.getId());
        }

        departmentMapper.updateByPrimaryKeySelective(department);
    }


    @Override
    public PageList<Department> pageList(DepartmentQuery departmentQuery) {
        PageHelper.startPage(departmentQuery.getCurrentPage(), departmentQuery.getPageSize());
        List<Department> departments = departmentMapper.pageList(departmentQuery);

        //拿到分页数据
        PageInfo<Department> pageInfo = new PageInfo<>(departments);
        //封装分页返回给前端的数据（total,list）
        PageList<Department> pageList = new PageList<>(pageInfo.getTotal(),pageInfo.getList());

        return pageList;
    }

    @Override
    public List<Department> getDeptTree() {
        //1.查询所有的部门数据，作为递归的基础数据
        List<Department> departments = departmentMapper.getDeptTree();
        //2.通过递归工具类，解析成无限极数据
        List<Department> tree = TreeUtil.getTree(departments);
        return tree;
    }


}
